let todoState = {
  todos:JSON.parse(localStorage.getItem("todo"))||[],
  showTodos:JSON.parse(localStorage.getItem("todo"))||[]
}

export function todoReducer(state = todoState ,action) {
  // console.log(action);
  switch (action.type){
    case "add":
      var flag = false;
      state.todos.forEach(element=>{
        if(element.val===action.todo.val){
          flag = true;
        }
      })

      if(flag){
        alert("不能重复添加");
        return state;
      }

      state.todos.push(action.todo);
      localStorage.setItem("todo",JSON.stringify(state.todos))
      return{
        todos:[...state.todos],
        showTodos:[...state.todos]
      }

      case "changestatus":
        state.todos.forEach((item)=>{
          if(item.val === action.todo.val){
            item.status = action.checked?"1":"0"
            console.log(item);
          }
        })
        localStorage.setItem("todo",JSON.stringify(state.todos))
        return{
          todos:[...state.todos],
          showTodos:[...state.todos]
        }

        case "delete":
      var tempIndex1 = state.todos.findIndex((item)=>{
        return item.val===action.todo.val;
      })
      var tempIndex2 = state.showTodos.findIndex((item)=>{
        return item.val===action.todo.val;
      })

      if(tempIndex1!=-1){
        state.todos.splice(tempIndex1,1);
      }

      if(tempIndex2!=-1){
        state.showTodos.splice(tempIndex2,1);
      }

      return{
        todos:[...state.todos],
        showTodos:[...state.showTodos]
      }

      case "all":
        return {
          todos:[...state.todos],
          showTodos:[...state.todos]
        }
      case "underway":
        state.showTodos = [];
        state.todos.forEach((item)=>{
          if(item.status === "0"){
            state.showTodos.push(item)
          }
        })
  
    return{
      todos:state.todos,
      showTodos:[...state.showTodos]
    } 
    case "fininshed":
      state.showTodos = [];
      state.todos.forEach((item)=>{
        if(item.status === "1"){
            state.showTodos.push(item)
          }
        })
        return{
          todos:state.todos,
          showTodos:[...state.showTodos]
        } 
    case "delAll":
      state.todos = []
      state.showTodos =[]
      localStorage.removeItem('todo')    
      return{
        todos:state.todos,
        showTodos:[...state.showTodos]
      } 

      default:
      return state
  }

}